import 'dart:io';

import 'package:amway_superapp_creator_plugin/config/enum_config.dart';
import 'package:amway_superapp_creator_plugin/models/circle_detail_model.dart';
import 'package:amway_superapp_creator_plugin/models/cover_images_model.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/utils/image_pickasset_util.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/base_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';


class EditCircleTopViewModel extends ChangeNotifier {


  CircleDetailData circle = CircleDetailData(medias: List<ImagesBean>());

  void setCircle(CircleDetailData circle, String amwayAda, String amwayId,
      List<ImagesBean> medias) {
    clear();
    this.circle = circle;
    this.circle.amwayId = amwayId;
    this.circle.ada = amwayAda;
    this.circle.medias = medias;
    num = circle.description != null ? circle.description.length : 0;
    if (medias != null) {
      readDatas(medias);
    }
  }

  List<CoverImagesModel> imageDatas = [];

  void addDatas(List<AssetEntity> selDatas) {
    isSelVideo = false;
    List<CoverImagesModel> coverDatas = [];
    List<Future<File>> uploadQueue = new List();
    selDatas.forEach((element) {
      if (element.type == AssetType.video) {
        isSelVideo = true;
      }
      uploadQueue.add(element.file);

    });
    Future.wait(uploadQueue)
        .then((results) {
      // print(results[0].toString()+results[1]);
      for (int i = 0; i < results.length; i++) {
        coverDatas.add(CoverImagesModel(file: results[i]));
      }

    })
        .catchError((e) {
      print(e);
    })
        .whenComplete(() {
      imageDatas.addAll(coverDatas);
      if (circle.medias == null) {
        circle.medias = new List<ImagesBean>();
      }
      circle.medias.addAll(coverDatas);
      notifyListeners();
    })
        .asStream();




  }

  void clear() {
    title = true;
    desc = true;
    imageDatas.clear();
    if (circle.products != null) {
      circle.products.clear();
    }
  }

  void readDatas(List<ImagesBean> image) {
    if (image != null) {
      List<Future<AssetEntity>> assetQueue = new List();
      image.forEach((element) {
        if (element.data.startsWith("https")) {
          imageDatas.add(CoverImagesModel(
              path: element.data,
              imageType: 1,
              fileId: element.fileId,
              officialFlag: element.officialFlag,
              state: element.imageVerify,
              dataType: "IMAGE"));
        } else {
          assetQueue.add(AssetEntity.fromId(element.fileId));
        }
      });
      if (assetQueue.length > 0) {
        Future.wait(assetQueue).then((value) {
          for (var entity in value) {
            if (entity != null) {
              if (entity.type == AssetType.video) {
                isSelVideo = true;
              }
              imageDatas.add(
                  CoverImagesModel(assetEntity: entity, fileId: entity.id));
            }
          }
          notifyListeners();
        });
      } else {
        notifyListeners();
      }
    }
  }

  void pickAsset(BuildContext context,  RequestType type,
       {
      List<AssetEntity> assets,
      int maxAssetsCount = 9,
      }) async {

     pickAssetCamera(context,type,length: imageDatas.length).then((value){
       if(value!=null){
         addDatas(value);
       }
     });

  }

  bool isSelVideo = false;

  int num = 0;
  bool title = true;

/*
* 标题
* */
  void hasTitle(bool title) {
    this.title = title;
  }

  bool desc = true;

/*
* 正文
* */
  void hasDesc(bool desc) {
    this.desc = desc;
  }

/*
* 正文
* */
  bool image = true;

  void hasImage(bool image) {
    this.image = image;
  }

  void setNum(int i) {
    this.num = i;
  }

  bool checked = true;

  void isChecked(bool check) {
    this.checked = check;
    notifyListeners();
  }

  void saveCircle(String ada, BoolStringCallBack callback) {
    HttpManager().post(
        url: "apis/v1/creator/circles/$ada",
        data: circle,
        tag: null,
        successCallback: (data) {
          return callback.call(true, "");
        },
        errorCallback: (data) {
          return callback.call(false, data.message);
        });
  }

  void updateCircle(String id, {BoolStringCallBack callback}) {
    HttpManager().put(
        url: "apis/v1/creator/circles/$id",
        data: circle,
        tag: null,
        successCallback: (data) {
          return callback.call(true, "");
        },
        errorCallback: (data) {
          return callback.call(false, data.message);
        });
  }

  int _currentIndex = 0;

  int get currentIndex => _currentIndex;

  set currentIndex(int value) {
    _currentIndex = value;
    notifyListeners();
  }

  void removeData(int index) {
    if (imageDatas.length > 0) {
      imageDatas.removeAt(index);
      notifyListeners();
    }
  }

  void clearData() {
    imageDatas.clear();
    notifyListeners();
  }

  ///上传图片
  void uploadMultiImages(
      List<CoverImagesModel> mCoverImagesModels, HttpSuccessCallback callback) {
    List<ImagesBean> resultPaths = new List();
    List<AssetEntity> assetEntityList = new List();

    mCoverImagesModels.forEach((element) {
      assetEntityList.add(element.assetEntity);
    });

    List<Future<String>> uploadQueue = new List();
    assetEntityList.forEach((element) {
      uploadQueue.add(uploadSingleImage(element.file));
    });

    Future.wait(uploadQueue)
        .then((results) {
          // print(results[0].toString()+results[1]);
          for (int i = 0; i < results.length; i++) {
            resultPaths.add(ImagesBean(
                data: results[i],
                no: i,
                dataType: EnumUtils.enumToString(DataType.IMAGE),
                officialFlag: EnumUtils.enumToString(OfficialFlag.NO)));
          }
          if (null != callback) {
            callback.call(resultPaths);
          }
        })
        .catchError((e) {
          callback.call(resultPaths);
          print(e);
        })
        .whenComplete(() {})
        .asStream();
  }

  Future<String> uploadSingleImage(Future<File> future) async {
    String path = await OssHelper.getOssConfiguration().then((result) {
      Map<String, dynamic> ossMsg = {
        "accessKeyId": result.data['data']['accessKeyId'],
        "accessKeySecret": result.data['data']['accessKeySecret'],
        "expiration": result.data['data']['expiration'],
        "securityToken": result.data['data']['securityToken']
      };
      return ossMsg;
    }).then((oss) => singleUploadImageWithConfig(future, oss));
    return path;
  }

  Future<String> singleUploadImageWithConfig(
      Future<File> file, Map<String, dynamic> ossMsg) async {
    String path = await file.then((f) => OssHelper.uploadToOss(f, ossMsg));
    return path;
  }
}
